package com.tensquare.chat.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tensquare.chat.config.HuanXinConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class HuanXinTokenService {

    private static final String tokenRedisKey = "HUANXIN_TOKEN";


    @Autowired
    private HuanXinConfig huanXinConfig;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    private static final ObjectMapper MAPPER = new ObjectMapper();

    public String getToken(){
        //先从redis中命中
        String cacheData = redisTemplate.opsForValue().get(tokenRedisKey);
        System.out.println(cacheData);
        if(cacheData == null || cacheData.equals("")){

            String url = this.huanXinConfig.getUrl()
                    +this.huanXinConfig.getOrgName()+"/"
                    +this.huanXinConfig.getAppName()+"/token";

            Map<String , Object> param = new HashMap<>();
            param.put("grant_type","client_credentials");
            param.put("client_id",this.huanXinConfig.getClientId());
            param.put("client_secret",this.huanXinConfig.getClientSecret());
            ResponseEntity<String> responseEntity = this.restTemplate.postForEntity(url, param, String.class);
            if (responseEntity.getStatusCodeValue()!= 200){
                return null;
            }
            String body = responseEntity.getBody();
            JsonNode jsonNode = null;
            try {
                jsonNode = MAPPER.readTree(body);
                String accessToken = jsonNode.get("access_token").asText();
                //过期时间（提前一天失效）
                long expires_in = jsonNode.get("expires_in").asLong() - 86400;
                //将token存入redis
                this.redisTemplate.opsForValue().set(tokenRedisKey,accessToken,expires_in, TimeUnit.SECONDS);
                return accessToken;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


        return cacheData;



    }

}
